package cn.anstone.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.anstone.pojo.User;
import cn.anstone.service.UserService;
import cn.anstone.util.MyResult;

/**
 * @author J.L.Lee
 * @date  Aug 15, 2017
 */
@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	UserService userService;
	
	@RequestMapping("/list")
	public String getAllUser(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum, Model model){
		
		PageHelper.startPage(pageNum,5);
		
		List<User> users = userService.getAllUser();
		
		PageInfo<User> page = new PageInfo<User>(users,5);
		
		model.addAttribute("pageInfo",page);
		
		return "index";
	}
	
	@RequestMapping("/AjaxList")
	@ResponseBody
	public MyResult getAllUserWithJson(
			@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {

		// 在查询之前只需要调用，传入页码，以及每页的大小
		PageHelper.startPage(pageNum, 5);
		
		// startPage后面紧跟的这个查询就是一个分页查询
		List<User> users = userService.getAllUser();
		
		// 使用pageInfo包装查询后的结果，只需要将pageInfo交给页面就行了。
		// 封装了详细的分页信息,包括有我们查询出来的数据，传入连续显示的页数
		PageInfo pageInfo = new PageInfo(users, 5);
		
		return MyResult.ok(pageInfo);
	}
	
	@RequestMapping("/check")
	@ResponseBody
	public MyResult checkuser(@RequestParam("username")String username){
		//先判断用户名是否是合法的表达式;
		String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})";
		
		try {
			
			username = new String(username.getBytes("iso8859-1"),"utf-8");
			
		} catch (UnsupportedEncodingException e) {
			
			e.printStackTrace();
		}
		
		//System.out.println(username);
		
		if(!username.matches(regx)){
			
			return MyResult.build(300, "用户名必须是6-16位数字和字母的组合或者2-5位中文");
		}
		
		//数据库用户名重复校验
		boolean b = userService.checkUser(username);
		
		if(b){
			
			return MyResult.build(200, "用户名可用");
			
		}else{
			
			return MyResult.build(100, "用户名已被注册");
		}
	}
	
	
	/**
	 * 保存
	 * 1、支持JSR303校验
	 * 2、导入Hibernate-Validator
	 * 
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	@ResponseBody
	public MyResult create(@Valid User user,BindingResult result){
		
		System.out.println(user.getUsername());
		System.out.println(user.getEmail());
		System.out.println(user.getGender());
		System.out.println(user.getRoleid());
		
		if(result.hasErrors()){
			
			//校验失败，应该返回失败，在模态框中显示校验失败的错误信息
			Map<String, Object> map = new HashMap<String, Object>();
			
			List<FieldError> errors = result.getFieldErrors();
			
			for (FieldError fieldError : errors) {
				
				System.out.println("错误的字段名："+fieldError.getField());
				
				System.out.println("错误信息："+fieldError.getDefaultMessage());
				
				map.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			
			
			System.out.println("验证不通过");
			
			return MyResult.build(500, "验证不通过");
			
		}else{
			
			System.out.println("验证通过");
			
			userService.saveUser(user);
			
			return MyResult.ok();
		}
		
	}
	
	
	/**
	 * 根据id查询用户
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/getById/{id}",method=RequestMethod.GET)
	@ResponseBody
	public MyResult getUserById(@PathVariable("id")Integer id){
		
		User user = userService.getUserById(id);
		
		return MyResult.ok(user);
	}
	
	
	/*
	 * 解决方案；
	 * 我们要能支持直接发送PUT之类的请求还要封装请求体中的数据
	 * 1、配置上HttpPutFormContentFilter；
	 * 2、他的作用；将请求体中的数据解析包装成一个map。
	 * 3、request被重新包装，request.getParameter()被重写，就会从自己封装的map中取数据
	 * 员工更新方法
	 * @param employee
	 * @return
	 */
	@RequestMapping(value="/update/{id}",method=RequestMethod.PUT)
	@ResponseBody
	public MyResult update(User user,HttpServletRequest request){
		
		System.out.println("请求体中的值："+request.getParameter("gender"));
		
		System.out.println("将要更新的员工数据："+user);
		
		userService.updateUser(user);
		
		return MyResult.ok();
	}
	
	/**
	 * 单个批量二合一
	 * 批量删除：1-2-3
	 * 单个删除：1
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/delete/{ids}",method=RequestMethod.DELETE)
	public MyResult deleteUser(@PathVariable("ids")String ids){
		//批量删除
		if(ids.contains("-")){
			List<Integer> del_ids = new ArrayList<Integer>();
			String[] str_ids = ids.split("-");
			//组装id的集合
			for (String string : str_ids) {
				del_ids.add(Integer.parseInt(string));
			}
			userService.deleteBatch(del_ids);
		}else{
			Integer id = Integer.parseInt(ids);
			userService.deleteUserById(id);
		}
		return MyResult.ok();
	}
}
